package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 订单延迟消息监听组件
 * 监听延迟队列中的订单消息，处理超时未支付订单
 */
@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final IOrderService orderService;

    // 远程调用支付服务
    private final PayClient payClient;

    /**
     * 监听订单延迟消息
     * 处理延迟队列中到期的订单消息，检查订单支付状态
     *
     * @param orderId 订单ID
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME, delayed = "true"),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelayMessage(Long orderId) {

        // 1. 查询订单信息
        Order order = orderService.getById(orderId);

        // 2. 校验订单有效性和状态
        // 仅处理存在且状态为1即未支付的订单
        if (order == null || order.getStatus() != 1) {
            // 订单不存在或状态已变更，直接返回
            return;
        }

        // 3. 调用支付服务查询支付订单状态
        PayOrderDTO payOrder = payClient.queryPayOrderByBizOrderNo(orderId);

        // 4. 根据支付状态执行不同逻辑
        if (payOrder != null && payOrder.getStatus() == 3) {
            // 4.1 支付订单状态为"已支付"(3)，标记订单为支付成功
            orderService.markOrderPaySuccess(orderId);
        } else {
            // 4.2 未支付或支付状态异常，取消订单并释放资源
            orderService.cancelOrder(orderId);
        }
    }
}